package com.begamer.card.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.begamer.card.cache.Cache;
import com.begamer.card.cache.MailThread;
import com.begamer.card.cache.PlayerInfo;
import com.begamer.card.common.Constant;
import com.begamer.card.common.util.Random;
import com.begamer.card.common.util.RequestUtil;
import com.begamer.card.common.util.Statics;
import com.begamer.card.common.util.StringUtil;
import com.begamer.card.common.util.binRead.BagCostData;
import com.begamer.card.common.util.binRead.DaylyData;
import com.begamer.card.common.util.binRead.EnergyupData;
import com.begamer.card.common.util.binRead.RuneData;
import com.begamer.card.common.util.binRead.RuneTotalData;
import com.begamer.card.common.util.binRead.VipData;
import com.begamer.card.json.PlayerElement;
import com.begamer.card.json.command2.BuyBagJson;
import com.begamer.card.json.command2.BuyResultJson;
import com.begamer.card.json.command2.EnergyJson;
import com.begamer.card.json.command2.MailJson;
import com.begamer.card.json.command2.MailResultJson;
import com.begamer.card.json.command2.PlayerResultJson;
import com.begamer.card.json.command2.RuneJson;
import com.begamer.card.json.command2.RuneResultJson;
import com.begamer.card.json.command2.SignJson;
import com.begamer.card.json.command2.SignResultJson;
import com.begamer.card.log.ErrorLogger;
import com.begamer.card.log.PlayerLogger;
import com.begamer.card.model.pojo.LogBuy;
import com.begamer.card.model.pojo.Mail;

public class RuneController extends AbstractMultiActionController
{
	private static final Logger logger=Logger.getLogger(RuneController.class);
 	private static Logger playlogger =PlayerLogger.logger;
 	private static Logger errorlogger = ErrorLogger.logger;
 	
 	/**符文**/
 	public ModelAndView rune(HttpServletRequest request , HttpServletResponse response)
 	{
 		try{
			//检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if(checkResult != null)
			{
				return checkResult;
			}
			//获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			/***********************************修改部分 start************************************/
			//获取参数
			RuneJson rj=JSONObject.toJavaObject(jsonObject, RuneJson.class);
			RuneResultJson rrj=new RuneResultJson();
			//获取请求的数据
			PlayerInfo pi=Cache.getInstance().getPlayerInfo(rj.playerId,request.getSession());
			if(pi!=null)
			{
				if(UiController.checkMode(5, pi))
				{
					int page=rj.page;
					if(pi.player.getNewPlayerType()==22)//新手符文
					{
						pi.player.setNewPlayerType(pi.player.getNewPlayerType()+1);
					}
					if(page>=1 && page<=6)
					{
						RuneData rd=pi.player.getNextRune(page);
						if(rd!=null)
						{
							//符文值不足
							if(pi.player.getRuneNum()<rd.cost)
							{
								rrj.errorCode=28;
							}
							else
							{
								int runeToalId =rd.id/100;
								RuneTotalData runeTotalData =RuneTotalData.getData(runeToalId);
								if(pi.player.getLevel()<runeTotalData.level)//校验解锁等级
								{
									rrj.errorCode =57;
								}
								else
								{
									pi.player.removeRuneNum(rd.cost);
									int roll=Random.getNumber(100);
									//成功,记录下最新的符文id,清空符文成功率增加值
									if(roll<rd.successrate+pi.player.getRuneAdd(page))
									{
										pi.player.setRune(page);
										pi.player.resetRuneAdd(page);
										playlogger.info("|区服："+Cache.getInstance().serverId+"|玩家："+pi.player.getId()+"|"+pi.player.getName()+"|等级："+pi.player.getLevel()+"|点亮符文"+rd.id+"成功");
										//判断本次的页数是否都已点亮
										if(pi.player.thisTimesFul())
										{
											//增加页数,清空点亮信息
											pi.player.updateRune();
										}
									}
									//失败
									else
									{
										pi.player.addRunePro(page,rd.upgrade);
										rrj.errorCode=30;
										playlogger.info("|区服："+Cache.getInstance().serverId+"|玩家："+pi.player.getId()+"|"+pi.player.getName()+"|等级："+pi.player.getLevel()+"|点亮符文"+rd.id+"失败");
									}
									//更新成就
									String runeId =pi.player.getRuneId();
									if(runeId !=null && runeId.length()>0)
									{
										String [] ss =runeId.split("-");
										int num=0;
										for(int i=1;i<ss.length;i++)
										{
											num =StringUtil.getInt(ss[i])+num;
										}
										num =num+(StringUtil.getInt(ss[0])-1)*72;
										pi.player.updateAchieve(14,num+"");
									}
								}
							}
						}
					}
					else
					{
						playlogger.info("|区服："+Cache.getInstance().serverId+"|玩家："+pi.player.getId()+"|"+pi.player.getName()+"|等级："+pi.player.getLevel()+"|打开符文界面");
					}
					//设置返回结果
					rrj.id=pi.player.getRune();
					rrj.num=pi.player.getRuneNum();
					rrj.pro=pi.player.getRuneAdd();
				}
				else
				{
					rrj.errorCode =56;
				}
			}
			else
			{
				rrj.errorCode=-3;
			}
			Cache.recordRequestNum(rrj);
			String msg = JSON.toJSONString(rrj);
			/***********************************修改部分 end**************************************/
			logger.info("msg:"+msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e) 
		{
			errorlogger.error(this.getClass().getName()+"->"+Thread.currentThread().getStackTrace()[1].getMethodName()+"():",e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
 	}
 	
 	/**签到**/
 	public ModelAndView sign(HttpServletRequest request , HttpServletResponse response)
 	{
 		try{
			//检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if(checkResult != null)
			{
				return checkResult;
			}
			//获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			/***********************************修改部分 start************************************/
			//获取参数
			SignJson rj=JSONObject.toJavaObject(jsonObject, SignJson.class);
			SignResultJson srj=new SignResultJson();
			//获取请求的数据
			PlayerInfo pi=Cache.getInstance().getPlayerInfo(rj.getPlayerId(),request.getSession());
			if(pi!=null)
			{
				int signTimes=pi.player.getSignTimes();
				if(Statics.isTodaySign(pi))
				{
					//今天已签到
					srj.errorCode=66;
				}
				else
				{
					DaylyData dd=DaylyData.getData(signTimes);
					if(dd!=null)
					{
						int num =dd.number;
						if(dd.viptype ==1 && pi.player.getVipLevel()>=dd.viplevel && pi.player.getVipLevel()>0)
						{
							num =num*2;//vip特定天数特定等级签到双倍奖励
						}
						List<Integer> cardIds =new ArrayList<Integer>();
						//获取奖励
						switch (dd.type)
						{
						case 1://卡牌
							cardIds.add(dd.cardID);
							for(int i=0;i<num;i++)
							{
								pi.addCard(dd.cardID, 1);
							}
							break;
						case 2://装备
							for(int i=0;i<num;i++)
							{
								pi.addEquip(dd.cardID);
							}
							break;
						case 3://主动技能
							for(int i=0;i<num;i++)
							{
								pi.addSkill(dd.cardID,1);
							}
							break;
						case 4://被动技能
							for(int i=0;i<num;i++)
							{
								pi.addPassiveSkill(dd.cardID);
							}
							break;
						case 5://道具
							pi.addItem(dd.cardID, num);
							break;
						case 6://符文值
							pi.player.addRuneNum(num);
							break;
						case 7://钻石
							pi.player.addCrystal(num);
							break;
						case 8://金罡心
							pi.player.addDiamond(num);
							break;
						case 9://金币
							pi.player.addGold(num);
							break;
						}
						if(cardIds.size()>0)
						{
							pi.getNewUnitSkill(cardIds);
						}
					}
					
					//签到成功
					pi.player.addSignTimes();
					pi.player.setLastSignTime(StringUtil.getDateTime(System.currentTimeMillis()));
					//设置返回
					srj.times=pi.player.getSignTimes();
					srj.mark=1;
					srj.days=StringUtil.getDayNumsOfThisMonth();
					playlogger.info("|区服："+Cache.getInstance().serverId+"|玩家："+pi.player.getId()+"|"+pi.player.getName()+"|等级："+pi.player.getLevel()+"|签到");
				}
			}
			else
			{
				srj.errorCode=-3;
			}
			Cache.recordRequestNum(srj);
			String msg = JSON.toJSONString(srj);
			/***********************************修改部分 end**************************************/
			logger.info("msg:"+msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e) 
		{
			errorlogger.error(this.getClass().getName()+"->"+Thread.currentThread().getStackTrace()[1].getMethodName()+"():",e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
 	}
 	
 	/**购买怒气**/
 	public ModelAndView energy(HttpServletRequest request , HttpServletResponse response)
 	{
 		try{
			//检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if(checkResult != null)
			{
				return checkResult;
			}
			//获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			/***********************************修改部分 start************************************/
			//获取参数
			EnergyJson ej=JSONObject.toJavaObject(jsonObject, EnergyJson.class);
			PlayerResultJson prj=new PlayerResultJson();
			//获取请求的数据
			PlayerInfo pi=Cache.getInstance().getPlayerInfo(ej.getPlayerId(),request.getSession());
			if(pi!=null)
			{
				int number=EnergyupData.getNumber(pi.player.getMaxEnergy());
				EnergyupData ed=EnergyupData.getData(number+1);
				VipData vData =VipData.getVipData(pi.player.getVipLevel());
				if(vData !=null)
				{
					//校验阶段
					if(ed !=null)
					{
						if(vData.maxenergy ==0)//校验vip等级是否可以购买怒气
						{
							prj.errorCode =70;
						}
						if(prj.errorCode ==0)//校验购买次数
						{
							if(number>=vData.maxenergy)
							{
								prj.errorCode =72;
							}
						}
						if(prj.errorCode ==0)//校验购买所需钻石
						{
							if(pi.player.getTotalCrystal()<ed.cost)
							{
								prj.errorCode=71;
							}
						}
						//功能阶段
						if(prj.errorCode==0)
						{
							int[] crystals=pi.player.removeCrystal(ed.cost);
							MailThread.getInstance().addLogbuy(LogBuy.createLogBuy(pi.player.getId(), "购买怒气",crystals));
							pi.player.setMaxEnergy(pi.player.getMaxEnergy()+ed.energy);
							PlayerElement pe=new PlayerElement();
							pe.setData(pi.player);
							List<PlayerElement> list=new ArrayList<PlayerElement>();
							list.add(pe);
							prj.list=list;
						}
					}
					else
					{
						errorlogger.info("energyupdata is null");
					}
				}
				else
				{
					errorlogger.info("vipdata is null");
				}
			}
			else
			{
				prj.errorCode=-3;
			}
			Cache.recordRequestNum(prj);
			String msg = JSON.toJSONString(prj);
			/***********************************修改部分 end**************************************/
			logger.info("msg:"+msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e) 
		{
			errorlogger.error(this.getClass().getName()+"->"+Thread.currentThread().getStackTrace()[1].getMethodName()+"():",e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
 	}
 	
 	/**查看/领取邮件**/
 	public ModelAndView actionMail(HttpServletRequest request , HttpServletResponse response)
 	{
 		try{
			//检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if(checkResult != null)
			{
				return checkResult;
			}
			//获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			/***********************************修改部分 start************************************/
			//获取参数
			MailJson mj=JSONObject.toJavaObject(jsonObject, MailJson.class);
			MailResultJson mrj=new MailResultJson();
			//获取请求的数据
			PlayerInfo pi=Cache.getInstance().getPlayerInfo(mj.getPlayerId(),request.getSession());
			if(pi!=null)
			{
				int index=mj.i;
				int action=mj.t;
				List<Mail> mails=pi.getMails();
				if(index<0 || index>=mails.size())
				{
					mrj.errorCode=76;
				}
				else
				{
					//==操作:1打开,2领取附件==//
					Mail mail=mails.get(index);
					if(action==1)
					{
						if(mail.getState()==2)
						{
							if(!mail.haveAttach())
							{
								mail.setState(0);
								mail.setDeleteTime(Constant.MailKeepTime2);
							}
						}
						mrj.setData(mail);
					}
					else if(action==2)
					{
						if(mail.getState()!=2)
						{
							mrj.errorCode=77;
						}
						else
						{
							if(!mail.haveAttach())
							{
								mrj.errorCode=78;
							}
							else
							{
								pi.getMailAttach(mail);
								mail.setState(0);
								mail.clearAttach();
								mail.setDeleteTime(Constant.MailKeepTime2);
								mrj.setData(mail);
							}
						}
					}
					playlogger.info("|区服："+Cache.getInstance().serverId+"|玩家："+pi.player.getId()+"|"+pi.player.getName()+"|等级："+pi.player.getLevel()+"|打开/领取邮件|"+action+"|"+mail.getTitle());
				}
			}
			else
			{
				mrj.errorCode=-3;
			}
			Cache.recordRequestNum(mrj);
			String msg = JSON.toJSONString(mrj);
			/***********************************修改部分 end**************************************/
			logger.info("msg:"+msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e) 
		{
			errorlogger.error(this.getClass().getName()+"->"+Thread.currentThread().getStackTrace()[1].getMethodName()+"():",e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
 	}

 	/**购买背包**/
 	public ModelAndView buyBag(HttpServletRequest request , HttpServletResponse response)
 	{
 		try{
			//检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if(checkResult != null)
			{
				return checkResult;
			}
			//获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			/***********************************修改部分 start************************************/
			//获取参数
			BuyBagJson bbj=JSONObject.toJavaObject(jsonObject, BuyBagJson.class);
			BuyResultJson brj=new BuyResultJson();
			//获取请求的数据
			PlayerInfo pi=Cache.getInstance().getPlayerInfo(bbj.getPlayerId(),request.getSession());
			if(pi!=null)
			{
				int buyBagTimes=pi.player.getBuyBagTimes();
				BagCostData bd=BagCostData.getData(buyBagTimes+1);
				if(bd==null)
				{
					brj.errorCode=98;
				}
				else
				{
					//钻石
					if(bd.type==1)
					{
						if(pi.player.getTotalCrystal()<bd.cost)
						{
							brj.errorCode=71;
						}
						else
						{
							int[] crystals=pi.player.removeCrystal(bd.cost);
							MailThread.getInstance().addLogbuy(LogBuy.createLogBuy(pi.player.getId(), "购买背包上限",crystals));
							pi.player.addBuyBagTimes();
							brj.buyTimes=pi.player.getBuyBagTimes();
							brj.gold=pi.player.getGold();
							brj.crystal=pi.player.getTotalCrystal();
							if(pi.getPassiveSkillls().size()>=Statics.getPackageNum(pi))
							{
								brj.bagSizePs =0;
							}
							else
							{
								brj.bagSizePs =Statics.getPackageNum(pi)-pi.getPassiveSkillls().size();
							}
						}
					}
					//金币
					else
					{
						if(pi.player.getGold()<bd.cost)
						{
							brj.errorCode=89;
						}
						else
						{
							pi.player.removeGold(bd.cost);
							pi.player.addBuyBagTimes();
							brj.buyTimes=pi.player.getBuyBagTimes();
							brj.gold=pi.player.getGold();
							brj.crystal=pi.player.getTotalCrystal();
							if(pi.getPassiveSkillls().size()>=Statics.getPackageNum(pi))
							{
								brj.bagSizePs =0;
							}
							else
							{
								brj.bagSizePs =Statics.getPackageNum(pi)-pi.getPassiveSkillls().size();
							}
						}
					}
				}
			}
			else
			{
				brj.errorCode=-3;
			}
			Cache.recordRequestNum(brj);
			String msg = JSON.toJSONString(brj);
			/***********************************修改部分 end**************************************/
			logger.info("msg:"+msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e) 
		{
			errorlogger.error(this.getClass().getName()+"->"+Thread.currentThread().getStackTrace()[1].getMethodName()+"():",e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
 	}
}
